#Changed?
# Establish directories
# NB BRT Source Functions must be located in the working directory

in.dir = '/home1/99/jc152199/brt/data/'
setwd(in.dir)
out.dir = '/home1/99/jc152199/brt/data/'

# Load the gbm library to perform Boosted Regression Tree Analysis
necessary=c('gbm')
#check if library is installed
installed = necessary %in% installed.packages()
#if library is not installed, install it
if (length(necessary[!installed]) >=1) install.packages(necessary[!installed], dep = T)
#load the libraries
for (lib in necessary) library(lib,character.only=T)

# Read in data to model

model.data = read.csv('/home1/99/jc152199/MicroclimateStatisticalDownscale/ToAnalyse/MicroMacroMinMaxASCII.csv',header=T)

# Establish a list of parameters for the BRT model, including learning rate, tree complexity, and number of trees

lr.list = c(.1,.05,.025,.01,.005,.001)
tc.list = c(1,3,5)

# Establish a null object to write data into

cv.error.data = data.frame(learning.rate=NA,tree.complexity=NA,iteration=NA,optimal.tree.num=NA,cv.error=NA)	

	for (tc in tc.list)
	
	{

		for(lr in lr.list)
	
		{
 
		brt.gbm = gbm(formula = micro_max~AWAP_max+coastdist+fpcmean+fpcvar+roaddist+solar, distribution = "gaussian", data = model.data, n.trees = 4000, interaction.depth = tc, shrinkage = lr, bag.fraction = 0.5, cv.folds=10)
	
		op.tree.num = gbm.perf(brt.gbm, plot.it = FALSE, oobag.curve = FALSE, overlay = TRUE, method='cv')
	
		t.data = data.frame(learning.rate=c(rep(lr,brt.gbm$n.trees)),tree.complexity=c(rep(tc,brt.gbm$n.trees)),iteration=c(seq(1,brt.gbm$n.trees,1)),optimal.tree.num=c(rep(op.tree.num,brt.gbm$n.trees)),cv.error=c(brt.gbm$cv.error))

		cv.error.data = rbind(cv.error.data,t.data)
	
		}
	
	}
	
write.csv(cv.error.data, file='cv.error.summary.4000trees.csv',row.names=F)

#End
